<template>
  <div class="index-page">
    <carrousel :articles="article.data.data" :fetching="article.fetching" />
    <!-- <announcement :announcement="announcement" /> -->
    <article-list
      :articles="article.data.data"
      :fetching="article.fetching"
      :pagination="article.data.pagination"
      @loadmore="loadmoreArticles"
    />
  </div>
</template>

<script>
import { computed, defineComponent } from "vue";
import { useEnhandle } from "../enhandle";
import Carrousel from "@/components/archive/carousel.vue";
import ArticleList from "@/components/archive/list.vue";
import Announcement from "@/components/archive/announcement.vue";
import { nextScreen, scrollToTop } from "../utils/effects";
import { onClient } from "@/universal";
export default defineComponent({
  name: "Index",
  components: {
    Carrousel,
    Announcement,
    ArticleList,
  },
  setup() {
    const { store } = useEnhandle();
    const article = computed(() => store.state.article.list);
    const announcement = computed(() => store.state.announcement.data);

    const fetchArticles = (params) => {
      return store.dispatch("article/fetchList", params);
    };

    const fetchAnnouncements = () => {
      return store.dispatch("announcement/fetchList");
    };

    const loadmoreArticles = async () => {
      const targetPage = article.value.data.pagination?.page + 1;
      await fetchArticles({ page: targetPage });
      if (targetPage > 1) {
        onClient(nextScreen);
      }
    };

    const fetchAllData = () => {
      onClient(scrollToTop);
      return Promise.all([fetchArticles(), fetchAnnouncements()]);
    };

    fetchAllData();

    return {
      article,
      announcement,
      loadmoreArticles,
    };
  },
});
</script>
